<?php

namespace App\Admin\Forms\Stock;

use App\Admin\Services\StockService;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class ImportRecord extends Form
{
    /**
     * The form title.
     *
     * @var string
     */
    public $title = '库存进出记录导入';

    /**
     * Handle the form request.
     *
     * @param Request $request
     *
     * @return RedirectResponse
     * @throws \Box\Spout\Common\Exception\IOException
     * @throws \Box\Spout\Reader\Exception\ReaderNotOpenedException
     */
    public function handle(Request $request)
    {
        $reader = ReaderEntityFactory::createCSVReader();
        $reader->open($request->file('file'));

        $sheets = $reader->getSheetIterator();
        $sheets->rewind();
        $sheet = $sheets->current();

        $total = $hasSuccess = 0;
        $data = [];
        foreach ($sheet->getRowIterator() as $row) {
            $rowArr = $row->toArray();
            $total++;
            if (empty($rowArr[0]) || empty($rowArr[1]) || strlen($rowArr[0]) != 10) {
                continue;
            }
            if (empty($rowArr[1])) {
                continue;
            }

            $data[] = [
                'asin' => $rowArr[0],
                'value' => (int)$rowArr[1]
            ];
            if ($total % 60 == 0) {
                $hasSuccess += StockService::importStockRecord($data, Admin::user()->id);
                $data = [];
            }
        }
        $reader->close(); // 释放内存

        if ($data) {
            $hasSuccess += StockService::importStockRecord($data, Admin::user()->id);
        }

        admin_toastr("一共记录{$total}条，成功{$hasSuccess}条", "success", ['timeOut' => 5000]);

        return back();
    }

    /**
     * Build a form here
     */
    public function form()
    {
        $this->file('file', '请选择文件')
            ->rules('required', [
                'required' => '请选择上传文件',
                'mimes' => '请上传csv文件'
            ]);
    }

}
